package cn.dapeng.thread;

import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @BelongProject study
 * @BelongPackage cn.dapeng.thread
 * @Description TODO
 * @ClassName ThreadCommunicationT04
 * @Author xupenghong
 * @Date 2024/8/28 14:00
 * @Version 1.0.0
 */
public class ThreadCommunicationT07 {


    public static void main(String[] args) throws Exception {
        char[] aI = "1234567".toCharArray();
        char[] bI = "ABCDEFG".toCharArray();

        PipedInputStream input1 = new PipedInputStream();
        PipedInputStream input2 = new PipedInputStream();

        PipedOutputStream output1 = new PipedOutputStream();
        PipedOutputStream output2 = new PipedOutputStream();

        input1.connect(output2);
        input2.connect(output1);

        String msg = "Your turn";

        new Thread(() -> {
            byte[] b = new byte[9];
            try {
                for (char c : aI) {
                   input1.read(b);

                   if(new String(b).equals(new String(msg))) {
                       System.out.print(c);
                   }
                   output1.write(msg.getBytes());
                }

            } catch (Exception e) {

            }

        }, "T1").start();

        new Thread(() -> {
            byte[] b = new byte[9];
            try {
                for (char c : bI) {
                    System.out.print(c);
                    output2.write(msg.getBytes());
                    input2.read(b);
                    if(new String(b).equals(new String(msg))) {
                        continue;
                    }
                }

            } catch (Exception e) {

            }

        }, "T2").start();



    }

}
